<?php
session_start();
require_once 'db_connect.php';
require_once 'HerbManager.php';

// 检查用户是否已登录
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $herbManager = new HerbManager();
    
    $data = [
        'name' => $_POST['name'],
        'purchase_price' => $_POST['purchase_price'] ? (float)$_POST['purchase_price'] : null,
        'sale_price' => $_POST['sale_price'] ? (float)$_POST['sale_price'] : null,
        'shipping' => $_POST['shipping'],
        'category_price' => $_POST['category_price'] ? (float)$_POST['category_price'] : null,
        'effects' => $_POST['effects'],
        'contraindications' => $_POST['contraindications']
    ];
    
    $success = $herbManager->addHerb($data);
    
    if ($success) {
        echo json_encode(['success' => true, 'message' => '药材添加成功！']);
    } else {
        echo json_encode(['success' => false, 'message' => '添加失败，请重试']);
    }
    exit;
}

echo json_encode(['success' => false, 'message' => '无效请求']);
?>